import { Calendar, Select, Col, Row } from "antd";
import type { CalendarMode } from "antd/es/calendar/generateCalendar";
import locale from "antd/lib/calendar/locale/zh_CN.js";
import dayjs from "dayjs";
import { includes, head, last, forEach, map, sortBy, concat } from "lodash";
import type { Moment } from "moment";
import moment from "moment";

import { formatDate } from "~/modules/shared/utils/common";
import "./index.scss";

interface Props {
  flight: any;
  date: Function;
  year: string;
  month: string;
  onSelect: Function;
  taskDate: string[];
}
const CalendarComponent = (props: Props) => {
  let isSelectYearMonthEvent = false;
  const checkIsSelect = (value: Moment) => {
    if (includes(props.taskDate, formatDate(value))) {
      return "b";
    }
    if (
      moment(value).isBetween(
        head(props.taskDate),
        last(props.taskDate),
        null,
        "[]"
      )
    ) {
      return "b";
    }
    return "a";
  };

  const getListData = (value: Moment, flight: any) => {
    let listData: { class: string; content: string }[];
    const bgClass = checkIsSelect(value);
    listData = [
      {
        class: "",
        content: moment(value).format("DD"),
      },
    ];

    forEach(flight, (item) => {
      if (item.date === formatDate(value)) {
        listData = concat(
          listData,
          map(item.data, (takeoffTime: string) => {
            return {
              class: "li-class",
              content: moment(takeoffTime).utcOffset(0).format("HH:mm:ss"),
            };
          })
        );
      }
    });
    return { listData, bgClass };
  };

  const dateCellRender = (value: Moment) => {
    const { listData, bgClass } = getListData(value, props.flight);

    return (
      <div className={bgClass}>
        {listData.map(
          (item: { content: string; class: string }, index: number) => (
            <li className={item.class} key={index}>
              {item.content}
            </li>
          )
        )}
      </div>
    );
  };

  const onPanelChange = (date: Moment, mode: CalendarMode) => {
    props.date(date.format("YYYY"), date.format("MM"));
  };
  const onSelect = (value: Moment) => {
    if (isSelectYearMonthEvent) {
      return;
    }
    let selectDate = props.taskDate;
    if (selectDate.length >= 2) {
      selectDate = [];
      selectDate.push(formatDate(value));
    } else {
      selectDate.push(formatDate(value));
    }
    selectDate = sortBy(selectDate);

    props.onSelect(selectDate);
  };

  const handleChange = (
    callback: { (date: Moment): void; (arg0: any): void },
    date: Moment
  ) => {
    isSelectYearMonthEvent = true;
    callback(date);
    isSelectYearMonthEvent = false;
  };
  return (
    <>
      <Calendar
        locale={locale}
        headerRender={({ value, type, onChange, onTypeChange }) => {
          const start = 0;
          const end = 12;
          const monthOptions = [];
          let current = value.clone();
          const localeData = value.localeData();

          const months = [];
          for (let i = 0; i < 12; i++) {
            current = current.month(i);
            months.push(localeData.monthsShort(current));
          }
          for (let i = start; i < end; i++) {
            monthOptions.push(
              <Select.Option key={i} value={i} className="month-item">
                {months[i]}
              </Select.Option>
            );
          }
          const dateYear = Number(dayjs().format("YYYY"));
          const year = value.year();
          const month = value.month();
          const options = [];
          for (let i = dateYear; dateYear - 20 < i && i <= dateYear; i--) {
            options.push(
              <Select.Option key={i} value={i} className="year-item">
                {i}
              </Select.Option>
            );
          }
          return (
            <div>
              <Row gutter={16} justify="start">
                <Col>
                  <Select
                    dropdownMatchSelectWidth={false}
                    className="my-year-select"
                    style={{ width: "100px" }}
                    value={year}
                    onChange={(newYear) => {
                      const now = value.clone().year(newYear);
                      handleChange(onChange, now);
                    }}
                  >
                    {options}
                  </Select>
                </Col>
                <Col>
                  <Select
                    dropdownMatchSelectWidth={false}
                    value={month}
                    style={{ width: "100px" }}
                    onChange={(newMonth) => {
                      const now = value.clone().month(newMonth);
                      handleChange(onChange, now);
                    }}
                  >
                    {monthOptions}
                  </Select>
                </Col>
                <Col className="flex">
                  <Row align="middle">
                    当前选择日期：{head(props.taskDate)}~{last(props.taskDate)}
                  </Row>
                </Col>
              </Row>
            </div>
          );
        }}
        value={moment(`${props.year}-${props.month}-${moment().format("DD")}`)}
        dateFullCellRender={dateCellRender}
        onPanelChange={onPanelChange}
        onSelect={onSelect}
      />
    </>
  );
};

export default CalendarComponent;
